package com.etong.citymap.activity;

import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.etong.citymap.bean.ScreenBean;
import com.etong.citymap.connect.HttpSendData;
import com.etong.citymap.db.util.CityApplication;
import com.etong.citymap.service.TrajectorySerivice;
import com.etong.citymap.service.UploadSerivice1;
import com.etong.citymap.util.ActivityUtil;
import com.etong.citymap.util.DateUtil;
import com.etong.citymap.util.StringUtil;
import com.etong.citymap.util.log.LogDetailUtil;
import com.etong.citymap.util.log.LogUtil;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 数字城管主菜单
 */
public class MainActivity extends Activity implements OnItemClickListener {
	GridView gridView;
	TextView loginname;
	SharedPreferences preferences;
	public static final String HttpShareUrl = "http";
	public static final String HistoryShareUrl = "historytime";
	public static final String HttprefreshUrl = "httprefresh";

	private CityApplication cityApplication;
	public static String[] MainMenuName = { "问题上报", "我的任务", "历史记录", "今日提示", "地图浏览", "单键拨号", "使用帮助", "系统设置", "打卡下班" };
	public static Integer[] MainMenuIcon = new Integer[9]; // 和上面相对应的MainMenuName相对应的icon

	/** 授权文件路径 */
	private String licPath;
	/** 授权文件名字 */
	private String licName;

	/** 通知ID */
	final int NOTIFICATION_ID = 101;

	Handler handler = new Handler(new Handler.Callback() {

		@Override
		public boolean handleMessage(Message msg) {
			if (msg.what == 2) {
				String result = msg.getData().getString("result");
				if (result.equals("-3")) {
				} else if (result.equals("-1")) {
					Toast.makeText(MainActivity.this, "操作错误", Toast.LENGTH_SHORT).show();
				} else if (result.equals("-2")) {

				}
			} else if (msg.what == 3) {
				cityApplication.setTodayCueCountNo(msg.arg1);
				gridView.setAdapter(new ImageAdapter());
			}
			return false;
		}
	});

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.mainlayout);
		cityApplication = (CityApplication)getApplication();
		preferences = this.getSharedPreferences("data",	Context.MODE_WORLD_READABLE);
		init();
		cityApplication.setFristCamer(true);
		//Configure.IsFristCamer = true;
		startCustomService();
		tongzhilan();
		initdata();
	}

	void initdata() {
		cityApplication.setHistorySaveTime(preferences.getInt(HistoryShareUrl,1));
		cityApplication.setHTTPRefreshUrl(preferences.getString(HttprefreshUrl,cityApplication.getHTTPRefreshUrl()));
		//Configure.HTTPRefreshUrl = preferences.getString(HttprefreshUrl,Configure.HTTPRefreshUrl);
	}


	void savedata() {
		Editor editor = preferences.edit();
		editor.putString(HttpShareUrl, cityApplication.getHTTPURL());
		editor.putInt(HistoryShareUrl, cityApplication.getHistorySaveTime());
		editor.putString(HttprefreshUrl, cityApplication.getHTTPRefreshUrl());
		editor.commit();

	}

	void startCustomService() { // 启动服务
		Intent intent = new Intent(this, TrajectorySerivice.class);
		startService(intent);
	}

	private NotificationManager mNotificationManager;
	void tongzhilan() {// 通知栏
		final String PRIMARY_CHANNEL = "default";

		mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
		Notification.Builder mBuilder;
		//判断是否是8.0Android.O
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
			NotificationChannel chan1 = new NotificationChannel(PRIMARY_CHANNEL,
					"Primary Channel", NotificationManager.IMPORTANCE_DEFAULT);
			chan1.setLightColor(Color.GREEN);
			chan1.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
			mNotificationManager.createNotificationChannel(chan1);
			mBuilder = new Notification.Builder(this,PRIMARY_CHANNEL);
		} else {
			mBuilder = new Notification.Builder(this);
		}
		Intent notificationIntent = new Intent(this, MainActivity.class);
		notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
		PendingIntent intent = PendingIntent.getActivity(this, 0,
				notificationIntent, 0);
		mBuilder.setContentTitle("数字环卫提示语")//设置通知栏标题
				.setContentText("点击后从新返回到页面")//设置通知栏内容
				.setContentIntent(intent) //设置通知栏点击意图
				.setTicker("数字环卫提示语" + ":" + "点击后从新返回到页面") //通知首次出现在通知栏，带上升动画效果的
				.setWhen(System.currentTimeMillis())//通知产生的时间，会在通知信息里显示，一般是系统获取到的时间
				.setSmallIcon(R.drawable.icon);//设置通知小ICON
		Notification notify = mBuilder.build();
		notify.flags = Notification.FLAG_ONGOING_EVENT;
		mNotificationManager.notify(NOTIFICATION_ID, notify);
	}

	void init() {
		loginname = (TextView) findViewById(R.id.loginname);
		gridView = (GridView) findViewById(R.id.maingrid);
		gridView.setSelector(new ColorDrawable(Color.TRANSPARENT));
		gridView.setAdapter(new ImageAdapter());
		gridView.setOnItemClickListener(this);
		MainMenuIcon[0] = R.drawable.but1_selector;
		MainMenuIcon[1] = R.drawable.but2_selector;
		MainMenuIcon[2] = R.drawable.but3_selector;
		MainMenuIcon[3] = R.drawable.but4_selector;
		MainMenuIcon[4] = R.drawable.but5_selector;
		MainMenuIcon[5] = R.drawable.but6_selector;
		MainMenuIcon[6] = R.drawable.but7_selector;
		MainMenuIcon[7] = R.drawable.but8_selector;
		MainMenuIcon[8] = R.drawable.but9_selector;
		loginname.setText(cityApplication.getUserName() + "您好 ,欢迎使用环卫通");

		licPath = Environment.getExternalStorageDirectory() + this.getResources().getString(R.string.city_license);
		licName = "SuperMap iMobile Trial.slm";
		new Thread(new Runnable() {//下载授权文件
			@Override
			public void run() {
				downLicFile();
			}
		}).start();
	}

	@Override
	protected void onResume() {

		//出现错误时，通过缓存重新登录
		cityApplication.setUserId(preferences.getString(LoginActivity.UserId, ""));
		cityApplication.setUserCode(preferences.getString(LoginActivity.UserCode, ""));
		cityApplication.setUserName(preferences.getString(LoginActivity.UserName, ""));
		
		if(StringUtil.IsNull(cityApplication.getUserId())){
			try {
				new exituser();
				Intent intent = new Intent(MainActivity.this,  TrajectorySerivice.class); // 关闭服务
				Intent in=new Intent(MainActivity.this,UploadSerivice1.class);
				TrajectorySerivice.realStopService();
				stopService(intent);
				stopService(in);
				LogDetailUtil.e("MainActivity的onResume调用停止服务操作！！！");
				mNotificationManager.cancelAll(); // 关闭通知栏
				//savedata();
				System.exit(0);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		cityApplication.setImageList(null);
		cityApplication.setImageList_Net(null);
		//Configure.ImageList = null;
		//Configure.ImageList_Net = null;
		//Configure.locPoint = null;
		cityApplication.setLocPoint(null);
		new LoadingToday();
		super.onResume();
	}

	class ImageAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			return MainMenuName.length;
		}

		@Override
		public Object getItem(int position) {
			return position;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View view = LayoutInflater.from(MainActivity.this).inflate(
					R.layout.mainitem, null);
			TextView title = (TextView) view.findViewById(R.id.title);
			title.setText(MainMenuName[position]);
			ImageView tubiao = (ImageView) view.findViewById(R.id.tubiao);
			tubiao.setBackgroundResource(MainMenuIcon[position]);
			ScreenBean screen = ActivityUtil
					.getScreenWidthAndHeight(MainActivity.this);
			view.setLayoutParams(new GridView.LayoutParams(screen
					.getScreenWidth() / 3 - 5, screen.getScreenWidth() / 3 - 5));
			if (position == 3) {
				if (cityApplication.getTodayCueCountNo() > 0) {
					view.findViewById(R.id.main_count_bg).setVisibility(
							LinearLayout.VISIBLE);
					((TextView) view.findViewById(R.id.main_count)).setText(cityApplication.getTodayCueCountNo() + "");
				}
			}
			return view;
		}

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			xiaban();
			return true;
		}
		return super.onKeyUp(keyCode, event);
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
		System.out.println(cityApplication.getUserCode()+"====="+cityApplication.getHistorySaveTime());
		switch (position) {
			case 0:
				ActivityUtil.ToActivity(MainActivity.this, ProblemUploadActivity.class);
				break;
			case 1:
				ActivityUtil.ToActivity(MainActivity.this, MyAssignmentActivity.class);
				break;
			case 2:
				ActivityUtil.ToActivity(MainActivity.this, HistoryTakeNotesActivity.class);
				break;
			case 3:
				ActivityUtil.ToActivity(MainActivity.this, ToDayCueActivity.class);
				break;
			case 4:
				ActivityUtil.ToActivity(MainActivity.this, MapActivity.class);
				break;
			case 5:
				ActivityUtil.ToActivity(MainActivity.this, FastDialActivity.class);
				break;
			case 6:
				ActivityUtil.ToActivity(MainActivity.this, HelpActivity.class);
				break;
			case 7:
				ActivityUtil.ToActivity(MainActivity.this, SettingActivity.class);
				break;
			case 8: {
				xiaban();
				break;
			}
		}
	}

	void xiaban() {
		Builder builder = new Builder(MainActivity.this);
		builder.setTitle("提示");
		builder.setMessage("你确定要打开下班吗?");
		builder.setPositiveButton("取消", null);
		builder.setNegativeButton("下班", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				try {
					new exituser();
					Intent intent = new Intent(MainActivity.this, TrajectorySerivice.class); // 关闭服务
					Intent in=new Intent(MainActivity.this, UploadSerivice1.class);
					TrajectorySerivice.realStopService();
					stopService(intent);
					stopService(in);
					LogDetailUtil.e("MainActivity的xiaban调用停止服务操作！！！");
					if(null != mNotificationManager){
						mNotificationManager.cancelAll(); // 关闭通知栏
					}
					//savedata();
					LogUtil.unregistUtil();
					System.exit(0);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
		builder.show();
	}

	class exituser extends Thread {
		public exituser() {
			start();
		}

		@Override
		public void run() {
			try {
				String url = "supervisor/ashx/LoginOut.ashx"; // 001
				Map<String, String> map = new HashMap<String, String>();
				map.put("flag", "0");
				 HttpSendData.SendGet(url, map, "utf-8",cityApplication.getHTTPURL());
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}

	class LoadingToday extends Thread {
		public LoadingToday() {
			start();
		}

		@Override
		public void run() {
			String url = "supervisor/ashx/TipList.ashx"; // 001 001
			Map<String, String> map = new HashMap<String, String>();
			map.put("superid", cityApplication.getUserId());
			map.put("tipdate",
					DateUtil.setSimpleDateFormat(new Date(), "yyyy-MM-dd"));
			map.put("pageindex", 0 + "");
			map.put("pagecount", cityApplication.PageCount + "");
			try {
				String result = HttpSendData.SendGet(url, map, "utf-8",cityApplication.getHTTPURL());
				if (result.equals("-1") || result.equals("-3")
						|| result.equals("-2")) {
					Message message = new Message();
					message.getData().putString("result", result);
					message.what = 2;
					handler.sendMessage(message);
				} else {
					JSONArray jsonArray = new JSONArray(result);
					int count = 0;
					for (int i = 0; i < jsonArray.length(); i++) {
						JSONObject jsonObject = jsonArray.getJSONObject(i);
						String k = jsonObject.getString("isread");
						if (k.equals("0")) {
							count++;
						}

					}
					Message message = new Message();
					message.what = 3;
					message.arg1 = count;
					handler.sendMessage(message);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	private void downLicFile() {
		File dirFile = new File(licPath);
		File[] fileArr = dirFile.listFiles();
		for (File file : fileArr) {
			file.delete();
		}
		int i = HttpSendData.downFile(cityApplication.getHTTPURL() + "supervisor/ashx/key.txt", licPath, licName);
		LogDetailUtil.i("下载授权文件的返回值是：" + i);
		if (i == 0) {
			refreshLic();
		} else {
			Looper.prepare();
			new Builder(MainActivity.this).setTitle("提示").setMessage("授权文件获取错误，请联系管理员进行解决！").setPositiveButton("确定", null).show();
			Looper.loop();
		}
	}

	private void refreshLic() {
		File f = new File(licPath + "/" + licName);
		if (f.exists()) {
			try {
				InputStream instream = new FileInputStream(f);
				if (instream != null) {
					InputStreamReader inputreader = new InputStreamReader(instream);
					BufferedReader buffreader = new BufferedReader(inputreader);
					String line;
					// 分行读取
					while ((line = buffreader.readLine()) != null) {
						if (line.startsWith("ExpiredDate=")) {
							String expiredDateStr = line.substring("ExpiredDate=".length());
							LogDetailUtil.i("授权文件的过期时间：" + expiredDateStr);
							String currentDateStr = DateUtil.setSimpleDateFormat(new Date(),"yyyyMMdd");
							if(currentDateStr.compareTo(expiredDateStr) >= 0){
								LogDetailUtil.i("授权文件的已过期");
								Looper.prepare();
								new Builder(MainActivity.this).setTitle("提示").setMessage("授权文件已过期，请联系管理员进行解决！").setPositiveButton("确定", null).show();
								Looper.loop();
							}
						}
					}
					instream.close();
				}
			} catch (java.io.FileNotFoundException e) {
				Log.d("TestFile", "The File doesn't not exist.");
			} catch (IOException e) {
				Log.d("TestFile", e.getMessage());
			}
		} else {
			Looper.prepare();
			new Builder(MainActivity.this).setTitle("提示").setMessage("无授权文件，请联系管理员进行解决！").setPositiveButton("确定", null).show();
			Looper.loop();
		}
	}
}
